package com.freegeese.security.test.chapter2.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.HashSet;

/**
 * 认证域
 */
public class CustomRealm1 extends AuthorizingRealm {
    @Override
    public String getName() {
        return CustomRealm1.class.getSimpleName();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return UsernamePasswordToken.class.isAssignableFrom(token.getClass());
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 主体
        String principal = String.valueOf(token.getPrincipal());
        // 凭证
        String credentials = String.valueOf((char[]) token.getCredentials());
        if (!"a".equals(principal)) {
            throw new UnknownAccountException();
        }
        if (!"1".equals(credentials)) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(principal, credentials, getName());
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(new HashSet<>(Arrays.asList("admin", "test")));
        info.setStringPermissions(new HashSet<>(Arrays.asList("admin:create", "admin:delete", "test:create")));
        return info;
    }
}
